<?php

/** 
 * @author Administrator
 * 
 */
class Rechargecard_mdl extends \MY_Model {
	protected $_table = 'hs_rechargecard';
	
	
	/**
	 */
	public function __construct() {
		parent::__construct ();
		
	}
	public function generateCard($count,$amount,$adminId){
		$createTime = time();
		$flag = $this->getUUID();
		
		$insert = array();
		while ( ($count--) > 0 ) {
			$insert[] = array(
					'cardpwd'=>$this->getPwd(),
					'createTime'=>$createTime,
					'adminID'=>$adminId,
					'amount'=>$amount,
					'flag'=>$flag,
			);
			if( count($insert)>30 ){// 每30条入库一次;
				$this->insertBatch($insert);
				$insert = array();
			}
		}
		if( ! empty($insert) ){
			$this->insertBatch($insert);
		}
		return $flag;
	}
	
	private function getUUID(){
		$data = array();
		$serverFields = array('REQUEST_TIME','HTTP_USER_AGENT','LOCAL_ADDR','LOCAL_PORT','REMOTE_ADDR','REMOTE_PORT');
		foreach ($serverFields as $field){
			if( isset($_SERVER[$field]) ) $data[] = $_SERVER[$field];
		}
		
		$data[] = uniqid(mt_rand(1,9999),TRUE);
		
		if( function_exists('getmypid') ){
			$data[] = (string)getmypid();//获取PHP进程ID
		}else{
			$data[] = mt_rand(0, 9999);
		}
		if( function_exists('memory_get_usage') ){
			$data[] = (string)memory_get_usage();//当前内存占用
		}else{
			$data[] = mt_rand(0, 9999);
		}
		return strtoupper(md5(implode('-', $data)));
	}
	
	
	private function getPwd($count=16){
		$pwd = '';
		// 第一位不为0
		$count-=1;
		$pwd .= mt_rand(1, 9);		
		
		while ( ($count--) > 0 ) {
			$pwd .= mt_rand(0, 9);
		}
		return $pwd;
		
// 		static $str = '0123456789';
// 		$strlen = strlen($str);
// 		$rtn = '';
// 		while ( ($count--) >0) {
// 			$rtn.=$str[mt_rand(0, $strlen-1)];
// 		}
// 		return $rtn;
	}
	/**
	 * 获取一个排它锁
	 * @param int $id
	 * @return CardLock
	 */
	public function getCardLock($id){
		return new CardLock($id);
	}
	
	
}


class CardLock{
	private $isLock = false;
	private $fp;
	public function __construct($id) {
		$this->file = APPPATH."cache/recharge_card_lock_{$id}";
		
		$this->fp = fopen ( $this->file, "w+" );
		if (! flock ( $this->fp, LOCK_EX | LOCK_NB )) {
			$this->isLock = true;
		}else{
			$this->isLock = false;
		}
	}
	
	public function isLock(){
		return $this->isLock;
	}
	
	public function unlock(){
		if (NULL !== $this->fp) {
			fclose ( $this->fp );
		}
// 		if (file_exists ( $this->file )) {
// 			unlink ( $this->file );
// 		}
		$this->fp = NULL;
	}
}










